package com.boot.dog.web.security.util;

import com.alibaba.fastjson.JSON;
import com.boot.dog.common.constant.Const;
import com.boot.dog.common.util.ApiResult;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletResponse;

import java.io.PrintWriter;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@Slf4j
public class SecurityResult {

    public static final <T> void success(ServletResponse response, String message) {
        success(response, message, null);
    }

    public static final <T> void success(ServletResponse response, String message, T t) {
        of(response, Const.OK, message, t);
    }

    public static final <T> void fail(ServletResponse response, String message, T t) {
        of(response, Const.BAD_REQUEST, message, t);
    }

    public static final <T> void fail(ServletResponse response, String message) {
        fail(response, message, null);
    }

    public static final <T> void forbidden(ServletResponse response, String message) {
        of(response, Const.FORBIDDEN, message, null);
    }

    public static final <T> void unauthorized(ServletResponse response, String message) {
        of(response, Const.UNAUTHORIZED, message, null);
    }

    private static final <T> void of(ServletResponse response, Integer code, String message, T t) {
        ApiResult<T> apiResult = new ApiResult<>(code, message);
        if (t != null) {
            apiResult.setContent(t);
        }
        PrintWriter out = null;
        try {
            response.setContentType("application/json;charset=UTF-8");
            out = response.getWriter();
            out.println(JSON.toJSONString(apiResult));
        } catch (Exception e) {
            log.error("security Result Error", e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }

    }
}
